package com.ciwong.epaper.modules.me.ui;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.ui.EpaperFragment;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.me.adapter.ChooseSchoolAdapter;
import com.ciwong.mobilelib.bean.SchoolDetail;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.widget.listview.PullRefreshController;
import com.ciwong.mobilelib.widget.listview.PullRefreshListView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 选择学校
 *
 * @author bin
 * @version ciwong v.1.0 2015/8/10 17:08
 * @since ciwong v.1.0
 */
public class ChooseSchoolActivity extends BaseActivity
        implements PullRefreshController.PullRefreshListener {
    private int type;

    private EApplication mNApplication;

    private PullRefreshListView chooseSchoolLV;

    private ChooseSchoolAdapter chooseSchoolAdapter;

    private boolean isFirstLogin;

    private  int mTryCount=2;
    private List<SchoolDetail> mSchoolDetailList;
    private ImageView choose_school_go_back;

    @Override
    protected void preCreate() {
        Intent intent = getIntent();
        if (intent != null) {
            type = intent.getIntExtra(IntentFlag.INTENT_FLAG_TYPE,
                    IntentValue.ChooseSchoolType.CHOOSE_SCHOOL_TYPE_AUTO);
        }
    }

    @Override
    protected int setView() {
        return R.layout.activity_choose_school;
    }

    @Override
    protected void findViews() {
        chooseSchoolLV = (PullRefreshListView) findViewById(
                R.id.chooseSchoolLV);
        choose_school_go_back = (ImageView) findViewById(R.id.choose_school_go_back);
    }

    @Override
    protected void initEvent() {

        choose_school_go_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

    @Override
    protected void init() {
        //showMiddleProgressBar(getString(R.string.choose_school));
        //setRightBtnText(android.R.string.ok);
        hideTitleBar();
        mNApplication = (EApplication) getBaseApplication();
        SchoolDetail schoolDetail = mNApplication.getSchoolDetail();
        List<SchoolDetail> schoolDetails = new ArrayList<SchoolDetail>();
        chooseSchoolAdapter = new ChooseSchoolAdapter(this, schoolDetails,
                schoolDetail);
        chooseSchoolLV.setAdapter(chooseSchoolAdapter);

        //获取首次登录信息
        isFirstLogin = SerializableManager.getInstance().getIsFirstLogin(true);
    }

    @Override
    protected void loadData() {
        loadNetData();
    }

    @Override
    public void onBackPressed() {
        if (type != IntentValue.ChooseSchoolType.CHOOSE_SCHOOL_TYPE_AUTO) {
            super.onBackPressed();
        }
    }

    private void loadNetData() {
        try {
            MeDao.getInstance().getSchoolInfo(new BaseExtCallBack(ChooseSchoolActivity.this, EApplication.getInstance().getUserInfoBase().getUserId()+"") {


                @Override
                public void failed(Object data) {
                    hideMiddleProgressBar();
                    if (mSchoolDetailList == null || mSchoolDetailList.size() < 1) {
                        //缓存没有才提示
                        showToastError(R.string.school_error);
                    }

                    chooseSchoolLV.stopRefresh();
                    //重新刷新数据 获取网络失败的时候重复刷新
                    if (mTryCount > 0) {
                        mTryCount--;
                        loadData();
                    }

                }

                @Override
                public void failed(int errorCode, Object data) {
                    super.failed(errorCode, data);
                    hideMiddleProgressBar();
                    if (mSchoolDetailList == null || mSchoolDetailList.size() < 1) {
                        //缓存没有才提示
                        showToastError(R.string.school_error);
                    }
                    chooseSchoolLV.stopRefresh();
                    //重新刷新数据 获取网络失败的时候重复刷新
                    if (mTryCount > 0) {
                        mTryCount--;
                        loadData();
                    }
                }

                @Override
                public void success(Object data) {
                    CWLog.e("TAT", "【ChooeseSchool】  -loadNetData");
                    List<SchoolDetail> schoolDetails = (List<SchoolDetail>) data;
                    chooseSchoolAdapter.clear();
                    chooseSchoolAdapter.addAll(schoolDetails);
                    SchoolDetail schoolDetail = chooseSchoolAdapter
                            .getSchoolDetail();
                    int indexOf = schoolDetails.indexOf(schoolDetail);
                    if (schoolDetails.isEmpty() || indexOf == -1) {
                        schoolDetail = null;
                    } else {
                        schoolDetail = schoolDetails.get(indexOf);
                    }
                    mNApplication.setSchoolDetail(schoolDetail);
                    chooseSchoolAdapter.setSchoolDetail(schoolDetail);

                    SerializableManager.getInstance().serialize(
                            SerializableManager.SerializeKey.SHARE_KEY_CHOOSE_SCHOOL,
                            schoolDetail);

                    setResult(RESULT_OK);
                    SerializableManager.getInstance().serialize(
                            SerializableManager.SerializeKey.SHARE_KEY_ALL_SCHOOL,
                            (Serializable) schoolDetails);
                    hideMiddleProgressBar();
                    if (type == IntentValue.ChooseSchoolType.CHOOSE_SCHOOL_TYPE_AUTO) {
                        if (schoolDetails == null || schoolDetails.isEmpty()) {
                            String userPhone = SerializableManager.getInstance().getUserPhone(true);
                            //绑定手机号不为空时去执行（针对老帐号）
                            if (null != userPhone && !"".equals(userPhone)) {
                                isFirstLoginAction(isFirstLogin);
                            }
                            finish();
                        } else if (schoolDetails.size() == 1) {
                            chooseSchoolAdapter
                                    .setSchoolDetail(schoolDetails.get(0));
                            findViewById(getRightId()).performClick();
                        } else {
                            chooseSchoolAdapter
                                    .setSchoolDetail(schoolDetails.get(0));
                        }
                    }
                    chooseSchoolLV.stopRefresh();
                }
            });
        }catch (Exception e){
            e.getStackTrace();
        }

    }

    @Override
    public void onRefresh() {
        loadData();
    }

    @Override
    public void onLoadMore() {

    }

    /**
         * 登录动作判断
         */
    public void isFirstLoginAction(boolean isFirstLogin) {
        CWLog.e("TAT", "【ChooseSchoolActivity】 登录判断");

        //第一次登录时
        if (isFirstLogin) {
            CWLog.e("TAT", "【ChooseSchoolActivity】 第一次登录");
            CWLog.e("TAT", "【ChooseSchoolActivity】 跳转“书柜”页面");
            EpaperJumpManager.jumpToAddBook(R.string.go_back, ChooseSchoolActivity.this, EpaperFragment.REQ_CODE_TO_ADD_BOOK);


        } else {
            CWLog.e("TAT", "【ChooseSchoolActivity】 非一次登录");
            //跳转主界面

        }
    }
}
